<template>
  <div class="setRight">
    <el-drawer :visible.sync="drawerVisible" size="768px" :with-header="false" @close="cancelForm">
      <div class="drawerForm">
        <div class="pageTitle">
          <span class="titleBorder">|</span>
          <div class="titleText">
            {{ pageType === 'edit' ? '编辑' : '新增' }}{{ formData.rightType === 1 ? '菜单' : '权限' }}
          </div>
          <slot name="header" />
          <el-divider />
        </div>
        <el-form
          ref="formData"
          :model="formData"
          :rules="rules"
          label-suffix="："
          label-width="140px"
          style="flex: 1; margin: 0px 30px"
        >
          <el-row>
            <el-col :span="12"></el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="parentId" class="newFormItem">
                <template slot="label">
                  上级菜单：
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">如果是具体页面，必须设置上级菜单</div>
                    <i class="el-icon-info" style="font-size: 17px" />
                  </el-tooltip>
                </template>
                <el-tree-select
                  ref="treeSelect"
                  v-model="formData.parentId"
                  class="rightMenu"
                  popover-class="rightMenuPopper"
                  :select-params="{
                    multiple: false,
                    clearable: true
                  }"
                  :tree-params="treeParams"
                />
              </el-form-item>
              <el-form-item label="菜单名称" prop="rightName">
                <el-input
                  v-model="formData.rightName"
                  :maxlength="20"
                  show-word-limit
                  placeholder="请输入菜单名称"
                  class="show-word-limit"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单类型" prop="rightType">
                <el-radio-group v-model="formData.rightType">
                  <el-radio-button :label="1">菜单</el-radio-button>
                  <el-radio-button :label="2">权限</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="formData.rightType === 1" label="路由名称" prop="routerName">
                <el-input
                  v-model="formData.routerName"
                  :maxlength="100"
                  show-word-limit
                  placeholder="请输入路由名称"
                  class="show-word-limit-59"
                />
              </el-form-item>
              <el-form-item v-if="formData.rightType === 2" label="排序号" prop="orderId">
                <el-input-number
                  v-model="formData.orderId"
                  style="width: 100%"
                  :min="0"
                  :max="99999999999"
                  :precision="0"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="formData.rightType === 1" prop="path" class="newFormItem">
            <template slot="label">
              路由地址：
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">
                  访问的路由地址，如：“user”;
                  <br />
                  如需外链访问则以“http(s)://”开头，默认“_blank”在新窗口打开。
                </div>
                <i class="el-icon-info" style="font-size: 17px" />
              </el-tooltip>
            </template>
            <el-input
              v-model="formData.path"
              class="show-word-limit-59"
              :maxlength="245"
              show-word-limit
              placeholder="请输入路由地址"
            >
              <el-select slot="prepend" v-model="formData.prependPath" style="width: 90px" clearable>
                <el-option label="/" value="/" :disabled="!!formData.parentId"></el-option>
                <el-option label="http://" value="http://"></el-option>
                <el-option label="https://" value="https://"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item v-show="formData.rightType === 1" prop="component" class="newFormItem">
            <template slot="label">
              组件路径：
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">
                  访问的组件路径，如：“system/user/index”，默认在“views”目录下;
                  <br />
                  如果填写“Layout” ，则表示使用layout组件。
                </div>
                <i class="el-icon-info" style="font-size: 17px" />
              </el-tooltip>
            </template>
            <div style="display: flex">
              <el-cascader
                v-model="formData.component"
                :options="componentTreeData"
                clearable
                filterable
                style="width: 100%"
                @change="handleChangeComponent"
              ></el-cascader>
              <!-- <el-input v-model="
                formData.component"
                readonly
                placeholder="请输入组件路径"
              /> -->
            </div>
          </el-form-item>
          <el-form-item v-show="formData.rightType === 1" prop="redirect" class="newFormItem">
            <template slot="label">
              重定向地址：
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">
                  在面包屑中点击会重定向去的地址；
                  <br />
                  当填写“noRedirect”的时候该路由在面包屑导航中不可被点击。
                </div>
                <i class="el-icon-info" style="font-size: 17px" />
              </el-tooltip>
            </template>
            <el-input
              v-model="formData.redirect"
              class="show-word-limit-59"
              :maxlength="255"
              show-word-limit
              placeholder="请输入重定向地址"
            />
          </el-form-item>
          <el-form-item prop="rightCode" class="newFormItem">
            <template slot="label">
              权限标识：
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">控制器中定义的权限标识，如：“system:user:list”。</div>
                <i class="el-icon-info" style="font-size: 17px" />
              </el-tooltip>
            </template>
            <el-autocomplete
              v-model="formData.rightCode"
              class="show-word-limit-59"
              :maxlength="100"
              show-word-limit
              style="width: 100%"
              :fetch-suggestions="querySearch"
            ></el-autocomplete>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="formData.rightType === 1" label="排序号" prop="orderId">
                <el-input-number
                  v-model="formData.orderId"
                  style="width: 100%"
                  :min="0"
                  :max="99999999999"
                  :precision="0"
                  controls-position="right"
                />
              </el-form-item>
              <el-form-item label="禁用" prop="disable">
                <el-switch v-model="formData.disable" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item v-show="formData.rightType === 1" prop="alwaysShow" class="newFormItem">
                <template slot="label">
                  显示根路由：
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">
                      当一个路由下面的 children 声明的路由大于1个时，自动会变成嵌套的模式--如组件页面；
                      <br />
                      只有一个子路由时，会将这个子路由当做根路由显示在侧边栏--如引导页面；
                      <br />
                      若想不管路由下面的 children 声明的个数都显示根路由，可以设置 alwaysShow:
                      true，这样它就会忽略之前定义的规则，一直显示根路由。
                    </div>
                    <i class="el-icon-info" style="font-size: 17px" />
                  </el-tooltip>
                </template>
                <el-switch v-model="formData.alwaysShow" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item v-show="formData.rightType === 1" label="固钉" prop="affix">
                <el-switch
                  v-model="formData.affix"
                  :disabled="formData.component?.[0] === 'Layout'"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-show="formData.rightType === 1" label="菜单图标" prop="icon">
                <iconChoose
                  :default-value="formData.icon"
                  @change="
                    (val) => {
                      formData.icon = val
                    }
                  "
                />
              </el-form-item>

              <el-form-item label="隐藏" prop="hidden">
                <el-switch v-model="formData.hidden" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item v-show="formData.rightType === 1" prop="noCache" class="newFormItem">
                <template slot="label">
                  不缓存：
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">选择缓存则会被“keep-alive”缓存，需要匹配组件的“name”和地址保持一致。</div>
                    <i class="el-icon-info" style="font-size: 17px" />
                  </el-tooltip>
                </template>
                <el-switch v-model="formData.noCache" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注信息" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="drawerFooter" align="right">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { loadMenuTree } from '@/api/system-management'
import iconChoose from '@/components/iconChoose/index.vue'
export default {
  name: 'SetRight',
  components: { iconChoose },
  props: {
    rightCodeList: {
      type: Array,
      default: () => {
        return []
      }
    },
    componentTreeData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      drawerVisible: false,
      pageType: '',
      titleName: '',
      treeParams: {
        clickParent: true,
        filterable: false,
        'check-strictly': true,
        'default-expand-all': true,
        'expand-on-click-node': true,
        data: [],
        props: {
          children: 'children',
          label: 'label',
          disabled: 'disabled',
          value: 'id'
        }
      },
      formData: {},
      rules: {
        rightName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        routerName: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
        orderId: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
        component: [],
        rightCode: []
      }
    }
  },
  watch: {
    'formData.parentId': {
      handler(val) {
        if (val && this.formData.prependPath === '/') {
          this.formData.prependPath = ''
        }
      }
    },
    'formData.rightType': {
      handler(val) {
        if (val === 1) {
          this.rules.component = [{ required: true, message: '请选择组件路径', trigger: ['blur', 'change'] }]
          this.rules.rightCode = []
          this.$refs.formData?.clearValidate('rightCode')
        } else {
          this.rules.component = []
          this.rules.rightCode = [{ required: true, message: '请选择权限标识', trigger: ['blur', 'change'] }]
        }
      }
    }
  },
  methods: {
    is(type, currentRow) {
      this.pageType = type
      this.formData = currentRow
      this.drawerVisible = true
      loadMenuTree().then((res) => {
        let data = res.data
        let currentTree = this.findNode(data, currentRow.rightId, [])
        this.setMenuTreeDisable(currentTree)
        this.$refs.treeSelect.treeDataUpdateFun(data)
      })
    },
    setMenuTreeDisable(data) {
      data.forEach((item) => {
        item.disabled = true
        if (item.children && item.children.length > 0) {
          this.setMenuTreeDisable(item.children)
        }
      })
    },
    findNode(data, val, result) {
      data.forEach((item) => {
        if (item.id === val) {
          result.push(item)
          return false
        }
        if (item.children && item.children.length > 0) {
          this.findNode(item.children, val, result)
        }
        return true
      })
      return result
    },
    querySearch(queryString, cb) {
      var restaurants = this.rightCodeList
      var results = queryString
        ? restaurants.filter((item) => {
            return item.value.indexOf(queryString) != -1
          })
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    handleChangeComponent(val) {
      if (val?.[0] === 'Layout') {
        this.formData.affix = 0
      }
    },
    // 提交表单
    submitForm() {
      if (!this.formData.parentId && !this.formData.prependPath) {
        this.$notify.warning('上级菜单为空时，路由地址需要选择前缀')
        return
      }
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          this.$emit('submitForm', this.formData)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 取消表单
    cancelForm() {
      this.pageType = ''
      this.$emit('closeForm')
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.setRight {
  height: 100%;
  /deep/label {
    font-weight: 500;
  }
  .drawerForm {
    display: flex;
    flex-direction: column;
    height: 100%;
    .rightMenu {
      /deep/.el-select {
        width: 100%;
        .el-input__suffix {
          display: flex;
          align-items: center;
        }
      }
    }

    .newFormItem {
      /deep/.el-form-item__label {
        display: flex;
        align-items: center;
        justify-content: right;
      }
    }
  }
  .drawerFooter {
    justify-content: right;
    padding: 20px;
  }
  .pageTitle {
    padding-top: 15px;
    padding-left: 15px;
    font-size: 20px;
    .titleBorder {
      font-weight: bold;
      font-size: 22px;
      color: #00a0e9;
      margin-right: 5px;
    }
    .titleText {
      display: inline;
      padding-right: 20px;
      padding-left: 5px;
    }
  }
}
</style>
<style lang="less">
.rightMenuPopper {
  .el-tree-node.is-current > .el-tree-node__content .el-tree-node__label {
    color: #0062ff;
  }
}
</style>
